package com.volunteer.service.Impl;

import com.volunteer.bean.LoginParam;
import com.volunteer.bean.PasswordParam;
import com.volunteer.config.RedisComponent;
import com.volunteer.mapper.UserMapper;
import com.volunteer.model.User;
import com.volunteer.service.UserLoginService;
import com.volunteer.service.UserService;
import com.volunteer.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * UserService实现类
 *
 * @author willow
 * @version v.0.1
 * @date 2018年08月2日
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ServletUtil servletUtil;
    @Autowired
    private RedisComponent redisComponent;
    @Autowired
    private UserLoginService userLoginService;

    @Override
    public Result userLogin(LoginParam loginParam) {
        // 获取登陆参数
        String phone = loginParam.getPhone();
        String password = loginParam.getPassword();
        // 将密码进行加密
        String pwdMD5 = Util.oneEncryption(password);
        // 设置查询参数
        User userLogin = new User();
        userLogin.setPhone(Long.valueOf(phone));
        userLogin.setPassword(pwdMD5);
        User user = userMapper.userLogin(userLogin);
        // 判断是否有符合情况的用户
        if (null == user)
            return ResponseResult.genFailResult(Constants.DEFAULT_FAIL_USER_NOT_EXIST);
        // 创建sessionId
        String sid = servletUtil.createSessionId(user.getId());

        Map<String, String> map = new HashMap<>();
        map.put("token", sid);
        return ResponseResult.genSuccessResult(map);
    }

    @Override
    public Result resetPassword(PasswordParam passwordParam, Long userId) {
        // 判断参数是否错误
        if (null == passwordParam)
            return ResponseResult.genFailResult(Constants.DEFAULT_FAIL_PARAM_ERROR);
        // 获取参数
        String oldPwd = passwordParam.getOldPassword();
        String newPwd = passwordParam.getNewPassword();
        if (null == oldPwd || null == newPwd)
            return ResponseResult.genFailResult(Constants.DEFAULT_FAIL_PARAM_ERROR);
        // 加密
        String oldPwdMD5 = Util.oneEncryption(oldPwd);
        String newPwdMD5 = Util.oneEncryption(newPwd);
        // 校验旧密码
        if (!userMapper.selectByPrimaryKey(userId).getPassword().equals(oldPwdMD5))
            return ResponseResult.genFailResult(Constants.DEFAULT_FAIL_PASSWORD_ERROR);
        // 更新密码
        User user = new User();
        user.setId(userId);
        user.setPassword(newPwdMD5);
        user.setUpdateTime(new Date());
        userMapper.updateByPrimaryKeySelective(user);
        // 修改密码时，批量清楚已登录的用户token
        List<String> userTokenList = userLoginService.getTokenByUserId(userId);
        if (null != userTokenList && userTokenList.size() > 0) {
            redisComponent.delKeys(userTokenList);
            userLoginService.delByUserId(userId);
        }
        return ResponseResult.genSuccessResult();
    }

    @Override
    public Result userExit(String sid) {
        // 在缓存中移除用户信息
        redisComponent.removeObject(sid);
        return ResponseResult.genSuccessResult(Constants.DEFAULT_SUCCESS_LOGOUT_MESSAGE);
    }

    @Override
    public Result userInfo(Long userId) {
        // 缓存中获取
        Object object = redisComponent.getHashObject(Constants.REDIS_USER_MESSAGE, userId.toString());
        if (null != object)
            return ResponseResult.genSuccessResult(object);
        User user = userMapper.selectByPrimaryKey(userId);
        user.setPassword(null);
        // 加入缓存
        redisComponent.putHashObject(Constants.REDIS_USER_MESSAGE, userId.toString(), user);
        return ResponseResult.genSuccessResult(user);
    }

    @Override
    @Transactional
    public Result updateInfo(User user) {
        // 删除缓存中的用户信息记录
        if (redisComponent.hasHashObject(Constants.REDIS_USER_MESSAGE, user.getId().toString()))
            redisComponent.removeHashObject(Constants.REDIS_USER_MESSAGE, user.getId().toString());
        user.setUpdateTime(new Date());
        userMapper.updateByPrimaryKeySelective(user);
        return ResponseResult.genSuccessResult();
    }

    @Override
    @Transactional
    public Result register(User user, Long userId) {
        // 判断登陆的用户是否是管理员
        Integer userType = userMapper.userType(userId);
        // 登陆用户不是管理员，返回权限不足
        if (!userType.equals(1))
            return ResponseResult.genPermissions();
        // 对用户密码进行加密处理
        String password = user.getPassword();
        password = Util.oneEncryption(password);
        user.setPassword(password);
        user.setCreateTime(new Date());
        user.setUpdateTime(new Date());
        user.setType(1);
        // 存入数据库
        int i = userMapper.insertSelective(user);
        // 返回结果
        if (i <= 0) {
            return ResponseResult.genFailResult(Constants.DEFAULT_FAIL_REGISTER_MESSAGE);
        } else {
            return ResponseResult.genSuccessResult(Constants.DEFAULT_SUCCESS_REGISTER_MESSAGE);
        }
    }
}
